package com.bjpowernode.handlers;

import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTUtil;
import com.bjpowernode.constants.Constant;
import com.bjpowernode.entities.TUser;
import com.bjpowernode.result.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class AppAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        TUser tUser = (TUser) authentication.getPrincipal();
        String userJSON = JSONUtil.toJsonStr(tUser);
        String token = JWTUtil.createToken(Map.of("user", userJSON), Constant.SECRET.getBytes());
        redisTemplate.opsForValue().set(Constant.REDIS_TOKEN_KEY + tUser.getId(), token, 30L, TimeUnit.MINUTES);
        Result result = Result.builder().code(200).msg("登录成功").info(token).build();
        String json = JSONUtil.toJsonStr(result);
        response.getWriter().write(json);
    }
}
